const BITLY_API_KEY = "R_0da49e0a9118ff35f52f629d2d71bf07";

CmdUtils.CreateCommand({ 
  names: ["bitly", "shorten"],
  arguments: [{role: 'object', nountype: noun_arb_text, label: 'URL to shorten'}],
  icon: "http://bit.ly/favicon.png",
  author: {name: "Mskadu", email: "mskadu@gmail.com" },  
  home: "http://code.google.com/p/ubiquity-commands/wiki/",
  description: 'Replaces the selected URL with a shortened version from <a href="http://bit.ly">bit.ly</a><br/> And copies it to the clipboard for any further use',
  license: "GPL",
  preview: function preview(pblock, args) {
    pblock.innerHTML = "Your input is <b>" + args.object.html + "</b>.";
  },
  execute: function execute(args) {

    // Our URL Validation is pretty much a protocol prefix check for now
    if( /^(http|https|ftp)\:\/\//.test( args.object.text ) )
    {
      var shortUrl = this._shorten( args.object.text );    
      if( shortUrl != null ) 
      {
        //Replace selected URL, if we have one
        if ( CmdUtils.getSelection()!='' )
          CmdUtils.setSelection( shortUrl );

        CmdUtils.copyToClipboard(shortUrl);
        displayMessage( _("Here it is. Also copied to the clipboard: ") + shortUrl, this );

      }
    }
    else
      displayMessage( _("Emm .. Sorry, but this doesn't look like a valid Url"), this );
  },
  _shorten: function( url ) {
     
      if( url == '' || url == null ) return null;
      //CmdUtils.log( 'Url to shorten: ' + url );

      //Note: Bit.ly API docs - http://code.google.com/p/bitly-api/wiki/ApiDocumentation
      var shortUrl = null;
      var base_url = 'http://api.bit.ly/shorten';
      var params = {
         version: '2.0.1',
         login: 'bitlyapidemo',
         apiKey: BITLY_API_KEY,
         longUrl: url 
      }; //note: history has been switched off for privacy


      jQuery.ajax({
        type: "GET",
        url: base_url,
        data: params,
        dataType: "json",
        async: false,
        error: function( error_data ) {
          displayMessage(_("error - Url not shortened"), this);
        },
        success: function( success_data ) {          
          shortUrl = null ;  
          var data_str = '';          

          var results = success_data.results;
          for( var index in results )
          {
            var result =  results[index];

            //Announce-and-Terminate on bitly errors
            if( result['statusCode'] == 'ERROR' )
            {
              displayMessage( 'Error. Bit.ly said: ' + result['errorMessage'], this );
              return null;
            }
           
            //extract the shortened url
            shortUrl = result['shortUrl'];

            break; //just process the first one for now
          }
        }
      });

      //CmdUtils.log( 'Shortened Url' + shortUrl );
      return shortUrl;
  }
});
